package com.laundry.merchant.ui.orders

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.laundry.merchant.model.Address
import com.laundry.merchant.model.LaundryService
import com.laundry.merchant.model.Order
import com.laundry.merchant.model.OrderStatus
import java.util.Date

class OrdersViewModel : ViewModel() {

    private val _orders = MutableLiveData<List<Order>>()
    val orders: LiveData<List<Order>> = _orders

    private val _filteredOrders = MutableLiveData<List<Order>>()
    val filteredOrders: LiveData<List<Order>> = _filteredOrders

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    init {
        loadOrders()
    }

    private fun loadOrders() {
        _isLoading.value = true
        
        // Mock data - in real app, this would come from repository/API
        val mockAddress = Address(
            name = "张三",
            phone = "13800138000",
            address = "北京市朝阳区",
            detailAddress = "某某小区1号楼101室"
        )
        
        val mockService = LaundryService(
            id = 1,
            name = "普通洗衣",
            description = "日常衣物清洗",
            price = 15.0,
            imageUrl = "",
            category = "洗衣"
        )
        
        val mockOrders = listOf(
            Order(
                id = "ORD001",
                userId = "USER001",
                userName = "张三",
                userPhone = "13800138000",
                merchantId = "MERCHANT001",
                services = listOf(mockService),
                totalAmount = 15.0,
                status = OrderStatus.PENDING,
                pickupAddress = mockAddress,
                deliveryAddress = mockAddress,
                pickupTime = null,
                deliveryTime = null,
                createdAt = Date(),
                notes = "请小心处理"
            ),
            Order(
                id = "ORD002",
                userId = "USER002",
                userName = "李四",
                userPhone = "13900139000",
                merchantId = "MERCHANT001",
                services = listOf(mockService.copy(name = "干洗服务", price = 35.0)),
                totalAmount = 35.0,
                status = OrderStatus.IN_PROGRESS,
                pickupAddress = mockAddress.copy(name = "李四"),
                deliveryAddress = mockAddress.copy(name = "李四"),
                pickupTime = Date(System.currentTimeMillis() - 3600000), // 1 hour ago
                deliveryTime = null,
                createdAt = Date(System.currentTimeMillis() - 7200000), // 2 hours ago
                notes = ""
            ),
            Order(
                id = "ORD003",
                userId = "USER003",
                userName = "王五",
                userPhone = "13700137000",
                merchantId = "MERCHANT001",
                services = listOf(mockService.copy(name = "熨烫服务", price = 20.0)),
                totalAmount = 20.0,
                status = OrderStatus.COMPLETED,
                pickupAddress = mockAddress.copy(name = "王五"),
                deliveryAddress = mockAddress.copy(name = "王五"),
                pickupTime = Date(System.currentTimeMillis() - 86400000), // 1 day ago
                deliveryTime = Date(System.currentTimeMillis() - 3600000), // 1 hour ago
                createdAt = Date(System.currentTimeMillis() - 172800000), // 2 days ago
                notes = "已按时完成"
            )
        )
        
        _orders.value = mockOrders
        _filteredOrders.value = mockOrders.filter { it.status == OrderStatus.PENDING }
        _isLoading.value = false
    }

    fun filterOrders(status: OrderStatus?, isInProgress: Boolean = false) {
        val allOrders = _orders.value ?: return
        
        _filteredOrders.value = when {
            status != null -> allOrders.filter { it.status == status }
            isInProgress -> allOrders.filter { 
                it.status in listOf(
                    OrderStatus.ACCEPTED, 
                    OrderStatus.PICKED_UP, 
                    OrderStatus.IN_PROGRESS, 
                    OrderStatus.READY,
                    OrderStatus.DELIVERING
                )
            }
            else -> allOrders
        }
    }

    fun acceptOrder(orderId: String) {
        val allOrders = _orders.value?.toMutableList() ?: return
        val orderIndex = allOrders.indexOfFirst { it.id == orderId }
        
        if (orderIndex != -1) {
            allOrders[orderIndex] = allOrders[orderIndex].copy(status = OrderStatus.ACCEPTED)
            _orders.value = allOrders
            
            // Refresh filtered orders
            filterOrders(OrderStatus.PENDING)
        }
    }

    fun updateOrderStatus(orderId: String, newStatus: OrderStatus) {
        val allOrders = _orders.value?.toMutableList() ?: return
        val orderIndex = allOrders.indexOfFirst { it.id == orderId }
        
        if (orderIndex != -1) {
            allOrders[orderIndex] = allOrders[orderIndex].copy(status = newStatus)
            _orders.value = allOrders
            
            // Refresh current filter
            // This would need to be improved to maintain current filter state
        }
    }
}
